package com.kyzh.core.utils
import java.io.File

object FileUtils {



    private fun getFolderSize(path: String): Long {
        val file = File(path)
        var size: Long = 0
        try {
            val fileList = file.listFiles()
            fileList?.let {
                for (i in it.indices) {
                    if (it[i].isDirectory)
                        size += getFolderSize(fileList[i].path)
                    else
                        size += it[i].length()
                }
            }
        } catch (e: Exception) {
        }

        return size
    }

    fun formatSize(path: String):String{
        val size = getFolderSize(path)
        val length = size.toString().length
        return when {
            length<4 -> "$size B"
            length in 4..6 -> "${String.format("%.2f", (size.toFloat() / 1024))}KB"
            length in 7..9 -> "${String.format("%.2f", (size.toFloat() / 1048576))}MB"
            else -> "${String.format("%.2f", (size.toFloat() / 1073741824))}GB"
        }
    }
    fun deleteFileExceptFolder(path: String){
        val file = File(path)
        if (file.isDirectory){
            val files = file.listFiles()
            files?.let {
                for (i in it.indices){
                    deleteFileExceptFolder(it[i].path)
                }
            }
        }else{
            file.delete()
        }
    }

}
